import React, { PureComponent } from "react";
import s from "./index.scss";
import { connect } from "react-redux";

import TopDetail from "./TopDetail";
import BotDetail from "./BotDetail";

import { Flex, PullToRefresh } from "antd-mobile";

import calc from "assets/images/calc.png";
import AxHeader from 'components/AxHeader'
import { calculatorFlag , investmentFlag } from "actions/detail";
import Calculator from "./Calculator"
import Modal from 'antd/lib/Modal';
import {callApi} from 'app/utils'
import {hashHistory} from 'React-Router'

@connect(
  state => ({
    storeDetail: state.detail,
    login:state.login
  }),
  {
    calculatorFlag,
    investmentFlag
  }
)

export default class extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      show: true,
      flag: 1,
      refreshing: false,
      down: false,
      height: document.documentElement.clientHeight,
      visible: false,
      visible2: false,
      authFlag: '',
      bindCardFlag: '',
      payPasswdSetFlag: '',
      isPayment: '',
      dialogTitle:'',
      btnStr:'',
      clicked: 'none',
      number:'',
      investmentData:{}
    };
    this.countdown = this.countdown.bind(this)
    this.showModal = this.showModal.bind(this)
    this.handleOk = this.handleOk.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    this.investClick = this.investClick.bind(this)
    this.investAmount = this.investAmount.bind(this)
  }

  componentDidMount() {
    let that = this
    setTimeout(() => {
      this.countdown(this.props.profile)     
    }, 1000);

  
  }

  investAmount(e){
    this.setState({
      number:e.target.value
    })
  }

  showModal() {
    if (localStorage.getItem('userData') != undefined&&localStorage.getItem('userData')!=null) {
      let userData
      if(localStorage.getItem('userData')!=undefined&&localStorage.getItem('userData')!="undefined"){
          userData = JSON.parse(localStorage.getItem('userData'))
         }
        

      if (userData.authFlag == 0) {
        this.setState({
          authFlag: true,
          visible: true,
          dialogTitle: '江西银行资金存管',
          btnStr:'确认开户',
        });
      } else if (userData.bindCardFlag == 0) {
        this.setState({
          bindCardFlag: true,
          visible: true,
          dialogTitle: '绑卡',
          btnStr:'确认绑卡',
        });
      } else if (userData.payPasswdSetFlag == 0) {
        this.setState({
          payPasswdSetFlag: true,
          visible: true,
          dialogTitle: '设置支付密码',
          btnStr:'设置支付密码',
        });
      } else if (userData.isPayment == 0) {
        this.setState({
          isPayment: true,
          visible: true,
          dialogTitle: '存管缴费授权',
          btnStr:'授权',
        });
      } else {
    
        let { investmentFlag } = this.props
        
        if(this.props.storeDetail.investFlag==true){
          investmentFlag(false)  
          hashHistory.push({
            pathname:'/projectList/Detail/payInfo',query:{
              loanID:this.props.profile.loanId,
              number:this.state.number
            }
          })       
          return false
        }
        
        callApi('/loan/invest/sync',{loanId:this.props.profile.loanId,token:JSON.parse(localStorage.getItem('userData')).token},'POST').then((data)=>{
          if(data.success==true){
            this.setState({
              investmentData:data.data
            })
            investmentFlag(true)
          }  
        })  
        
      }
    }
  }

  p(s) {
    return s < 10 ? "0" + s : s;
  }

  handleOk() {
    let userData
    if(localStorage.getItem("userData")!="undefined"&&localStorage.getItem("userData")!=null){
       userData = JSON.parse(localStorage.getItem("userData"))
    }
    
    this.setState({
      visible: false,
    });
    if(this.state.authFlag==true){
      hashHistory.push('/my/bindBankCard')
    }
    if(this.state.bindCardFlag==true){
      hashHistory.push('/my/userBindBankCard')
    }
    if(this.state.payPasswdSetFlag==true){
     
      let getToken = {
          token: userData.token
      };
      callApi('/account/paypassword',getToken,"POST").then((data)=>{
        location.href = data.data.ret_url;
    })
    }
    if(this.state.isPayment==true){
      var getToken = {
        token: JSON.parse(localStorage.getItem("userData")).token
      };
      callApi('/account/payment/auth',getToken,"POST").then((data)=>{
          location.href = data.data.ret_url;
      })
    }
    
  
  }
  handleCancel(e) {
    this.setState({
      visible: false,
    });
  }

  countdown(item) {
    let that = this

    this.btnTimer = setInterval(() => {
      var h = $("#h" + item.loanId).text();
      var m = $("#m" + item.loanId).text();
      var s = $("#s" + item.loanId).text();
      if (s == 0) {
        s = 60;
        if (m == 0) {
          m = 60;
          if (h == 0) {
            $('#btnTimeBox').find('.btn1').hide()
            $('#btnTimeBox').find('.btn2').show()
            clearInterval(this.btnTimer);
          }
          $("#h" + item.loanId).text(that.p(h - 1));
        }
        $("#m" + item.loanId).text(that.p(m - 1));
      }
      $("#s" + item.loanId).text(that.p(s - 1));
    }, 1000);
  }

  btnStatus(data) {
    if(this.props.login.isLogin==false){
      return <Flex.Item onClick={()=>{
        hashHistory.push('/login')
      }} className={`btn2 ${s.right} `}>立即登录</Flex.Item>
    }
    else if (data.countdown == '1') {
      return <Flex.Item className={` ${s.right}`}>
        <Flex.Item className={`btn1 bg-gray ${s.right}`}>
          <span id={`h${data.loanId}`}>{this.p(data.countH)}</span>:
                      <span id={`m${data.loanId}`}>{this.p(data.countM)}</span>:
                      <span id={`s${data.loanId}`}>{this.p(data.countS)}</span>
        </Flex.Item>
        <Flex.Item className={`btn2 ${s.right} `} onClick={this.showModal} style={{ display: 'none' }}>立即投资</Flex.Item>
      </Flex.Item>
    } else {

      if (data.status == '300') {
        return <Flex.Item onClick={this.showModal} className={`btn2 ${s.right} `}>立即投资</Flex.Item>
      } else if (data.status == '400') {
        return <Flex.Item className={`btn3 bg-gray ${s.right}`}>立即投资</Flex.Item>
      } else if (data.status == '500') {
        return <Flex.Item className={`btn4 bg-gray ${s.right}`}>立即投资</Flex.Item>
      }
    }

  }

  calculatorClick(flag) {
    let { calculatorFlag ,investmentFlag} = this.props
    investmentFlag(false)
    calculatorFlag(flag)
  }
  investClick(flag) {
    let { investmentFlag ,calculatorFlag} = this.props
    calculatorFlag(false)
    investmentFlag(flag)
  }




  //销毁时解绑事件
  componentWillUnmount() {
    //重写组件的setState方法，直接返回空
    this.setState = (state, callback) => {
      return;
    };
  }




  render() {
    let { detail, profile } = this.props
    let flag = this.props.storeDetail.flag
    let investFlag = this.props.storeDetail.investFlag
    let state = this.state
    let btnStatus = this.btnStatus(profile)
    let {investmentData} = this.state
    return (
      <div className={`${s.detailBox}`}>
        <AxHeader />
        {JSON.stringify(detail) == '{}' ? null :
          <PullToRefresh
            ref={el => this.ptr = el}
            style={{
              height: this.state.height,
              overflow: 'auto',
            }}
            indicator={this.state.down ? {} : { deactivate: '' }}
            direction={this.state.down ? 'down' : 'up'}
            refreshing={this.state.refreshing}
            onRefresh={() => {
              if (this.state.down == false) {
                this.setState({ refreshing: true, down: true, flag: 2 });
              } else {
                this.setState({ refreshing: true, down: false, flag: 1 });
              }
              this.setState({ refreshing: false });
              document.documentElement.scrollTop = 0
            }}
          >
            {this.state.flag == 1 ? <TopDetail detail={detail} /> : <BotDetail props={this.props.props} detail={detail}  />}
            <div className={`${s.block}`}>
            </div>
          </PullToRefresh>
        }


        <Modal title={this.state.dialogTitle} visible={this.state.visible}
          onOk={this.handleOk} onCancel={this.handleCancel} okText={this.state.btnStr} >
          {state.authFlag ? <p>安心投携手江西银行为您提供更安全的资金存管服务  立即开户</p> : null}
          {state.bindCardFlag ? <p>安心投携手江西银行为您提供更安全的资金存管服务  绑卡</p> : null}
          {state.payPasswdSetFlag ? <p>安心投携手江西银行为您提供更安全的资金存管服务  设置支付密码</p> : null}
          {state.isPayment ?<div><p>为保证资金交易均由用户授权银行操作，安心投需要用户先进行缴费授权后，才能进行提现、投资、快捷充值等操作。</p> <p>我已阅读并同意<a href='#'>《授权自动缴费协议》</a></p></div> : null}
        </Modal>
        
        <div className={`${s.bottomBox}`} key="f">
          <Flex className={`${s.item} `} id="btnTimeBox" >
            <Flex.Item className={`${s.left}`}><img onClick={this.calculatorClick.bind(this, true)} src={calc} /></Flex.Item>
            {btnStatus}
          </Flex>
        </div>
        {flag ? <Calculator profile={profile} /> : null}
        {investFlag?<Flex className={`${s.investmentIpt}`}>
          <Flex.Item className={`${s.mask}`} onClick={this.investClick.bind(this,false)}></Flex.Item>
          <Flex.Item className={`${s.iptBox}`}>
            <Flex.Item className={`${s.oneItem}`}>
                <input type="number" value={this.state.number} onChange={this.investAmount} placeholder={`投资上限${investmentData.maxInvestAmount}元`}/>
            </Flex.Item>
            <Flex.Item className={`${s.Item}`}>
                用户金额:<span className={`color1`}>{investmentData.balance}</span>元
            </Flex.Item>
            <Flex.Item className={`${s.Item}`}>
                起投金额:<span className={`color1`}>{investmentData.minInvestAmount}</span>元
            </Flex.Item>
            <Flex.Item className={`${s.Item}`}>
                可投金额:<span className={`color1`}>{investmentData.maxInvestAmount}</span>元
            </Flex.Item>
          </Flex.Item>
        </Flex>:null}
        
        

      </div>
    );
  }
}
